<?php
/**
 * Created by PhpStorm.
 * User: Jason
 * Date: 2017/9/21
 * Time: 17:27
 */

namespace Home\Service;


use Think\Model;

class ImageSheetService extends Model
{
    /*首页曲谱最佳排行*/
    public function sheetImg($sheetIds)
    {
        $map = array(
            'sheet_id' => array('in', $sheetIds),
            'is_delete' => 0
        );

        $model = M('ImageSheet');
        $images = $model->alias('a')->field('a.image_id, a.sheet_id, b.url, b.listorder')->join('image b ON a.image_id = b.id')
            ->where($map)->order('a.image_id, b.listorder')->select();

        foreach ($images as $key => $val) {
            $imageSheetMap[$val['sheet_id']][] = $val;
        }

        return $imageSheetMap;
    }

    /**
     * 获取用户对曲谱的设置
     * @param $sheetId
     * @return array
     */
    public function sheetImgConfig($sheetId)
    {
        $user = session('user');
        $map = array(
            'user_id' => empty($user) ? 0 : $user['uid'],
            'sheet_id' => $sheetId
        );
        $res = M('ImageUserConfig')->where($map)->order('id')->select();
        if (!empty($res)) {
            $imgConfigs = array();
            foreach ($res as $val) {
                $imgConfigs[$val['image_id']] = $val;
            }
            return $imgConfigs;
        }
        return [];
    }

    /**
     * 保存曲谱图片与曲谱的数据
     * @param $imageIds
     * @param $id
     * @return mixed
     */
    public function saveRelation($imageIds, $sheetId, $creator)
    {
        $Model = D('ImageSheet');
        //step-0: 先删除历史数据
        /*$Model->where(array('sheet_id'=>$sheet_id))->save(array('is_delete' => 1));*/

        //step-1: 组织图片和谱单的关系
        $imageSheet = array();
        foreach ($imageIds as $key => $val) {
            $imageSheet[] = array(
                'sheet_id' => $sheetId,
                'image_id' => $val,
                'creator'  => $creator
            );
        }

        //step-2: 批量保存图片和谱单的关系
        return $Model->addAll($imageSheet);
    }
}